package com.yc.testupload.controller;

import com.google.gson.Gson;
import com.yc.testupload.dao.AccountDAO;
import com.yc.testupload.model.Account;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 账号管理Servlet
 * 处理账号的获取、添加、更新和删除操作
 */
@WebServlet("/api/accounts")
public class AccountsServlet extends HttpServlet {
    private static final Logger logger = LogManager.getLogger(AccountsServlet.class);
    private AccountDAO accountDAO;
    private Gson gson;
    private SimpleDateFormat dateFormat;

    @Override
    public void init() throws ServletException {
        super.init();
        accountDAO = new AccountDAO();
        gson = new Gson();
        dateFormat = new SimpleDateFormat("yyyy-MM-dd");
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // 设置响应类型为JSON
        response.setContentType("application/json; charset=UTF-8");
        response.setCharacterEncoding("UTF-8");

        try {
            // 从session中获取当前登录用户的userId
            HttpSession session = request.getSession(false);
            if (session == null || session.getAttribute("userId") == null) {
                response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
                Map<String, String> errorResponse = new HashMap<>();
                errorResponse.put("error", "用户未登录");
                gson.toJson(errorResponse, response.getWriter());
                return;
            }

            // 获取userId
            Integer userId = Integer.valueOf(session.getAttribute("userId").toString());
            logger.debug("从session获取userId: {}", userId);

            // 确保userId不为null
            if (userId == null) {
                response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
                Map<String, String> errorResponse = new HashMap<>();
                errorResponse.put("error", "无法获取用户信息");
                gson.toJson(errorResponse, response.getWriter());
                return;
            }

            // 获取账号列表
            List<Account> accounts = accountDAO.getAccountsByUserId(userId);

            // 将账号列表转换为JSON格式的响应数据
            List<Map<String, Object>> responseData = convertAccountsToResponseData(accounts);

            // 返回成功响应 - 格式调整为前端期望的格式（code=0和data数组）
            Map<String, Object> successResponse = new HashMap<>();
            successResponse.put("code", 0);
            successResponse.put("data", responseData);

            gson.toJson(successResponse, response.getWriter());

        } catch (Exception e) {
            logger.error("获取账号列表时出错: {}", e.getMessage(), e);
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            Map<String, String> errorResponse = new HashMap<>();
            errorResponse.put("error", "服务器内部错误: " + e.getMessage());
            gson.toJson(errorResponse, response.getWriter());
        }
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // 设置响应类型为JSON
        response.setContentType("application/json; charset=UTF-8");
        response.setCharacterEncoding("UTF-8");

        try {
            // 从session中获取当前登录用户的userId
            HttpSession session = request.getSession(false);
            if (session == null || session.getAttribute("userId") == null) {
                response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
                Map<String, String> errorResponse = new HashMap<>();
                errorResponse.put("error", "用户未登录");
                gson.toJson(errorResponse, response.getWriter());
                return;
            }

            // 获取userId
            Integer userId = Integer.valueOf(session.getAttribute("userId").toString());
            logger.debug("从session获取userId: {}", userId);

            // 解析请求体中的账号数据
            Account account = gson.fromJson(request.getReader(), Account.class);
            account.setUserId(userId);

            // 添加账号
            boolean success = accountDAO.addAccount(account);

            if (success) {
                response.setStatus(HttpServletResponse.SC_OK);
                Map<String, Object> successResponse = new HashMap<>();
                successResponse.put("status", "success");
                successResponse.put("message", "账号添加成功");
                gson.toJson(successResponse, response.getWriter());
            } else {
                response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
                Map<String, String> errorResponse = new HashMap<>();
                errorResponse.put("error", "账号添加失败");
                gson.toJson(errorResponse, response.getWriter());
            }
        } catch (Exception e) {
            logger.error("添加账号时出错: {}", e.getMessage(), e);
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            Map<String, String> errorResponse = new HashMap<>();
            errorResponse.put("error", "服务器内部错误: " + e.getMessage());
            gson.toJson(errorResponse, response.getWriter());
        }
    }

    @Override
    protected void doPut(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // 设置响应类型为JSON
        response.setContentType("application/json; charset=UTF-8");
        response.setCharacterEncoding("UTF-8");

        try {
            // 从session中获取当前登录用户的userId
            HttpSession session = request.getSession(false);
            if (session == null || session.getAttribute("userId") == null) {
                response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
                Map<String, String> errorResponse = new HashMap<>();
                errorResponse.put("error", "用户未登录");
                gson.toJson(errorResponse, response.getWriter());
                return;
            }

            // 获取userId
            Integer userId = Integer.valueOf(session.getAttribute("userId").toString());
            logger.debug("从session获取userId: {}", userId);

            // 解析请求体中的账号数据
            Account account = gson.fromJson(request.getReader(), Account.class);
            account.setUserId(userId);

            // 更新账号
            boolean success = accountDAO.updateAccount(account);

            if (success) {
                response.setStatus(HttpServletResponse.SC_OK);
                Map<String, Object> successResponse = new HashMap<>();
                successResponse.put("status", "success");
                successResponse.put("message", "账号更新成功");
                gson.toJson(successResponse, response.getWriter());
            } else {
                response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
                Map<String, String> errorResponse = new HashMap<>();
                errorResponse.put("error", "账号更新失败");
                gson.toJson(errorResponse, response.getWriter());
            }
        } catch (Exception e) {
            logger.error("更新账号时出错: {}", e.getMessage(), e);
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            Map<String, String> errorResponse = new HashMap<>();
            errorResponse.put("error", "服务器内部错误: " + e.getMessage());
            gson.toJson(errorResponse, response.getWriter());
        }
    }

    @Override
    protected void doDelete(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // 设置响应类型为JSON
        response.setContentType("application/json; charset=UTF-8");
        response.setCharacterEncoding("UTF-8");

        try {
            // 从session中获取当前登录用户的userId
            HttpSession session = request.getSession(false);
            if (session == null || session.getAttribute("userId") == null) {
                response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
                Map<String, String> errorResponse = new HashMap<>();
                errorResponse.put("error", "用户未登录");
                gson.toJson(errorResponse, response.getWriter());
                return;
            }

            // 获取userId
            Integer userId = Integer.valueOf(session.getAttribute("userId").toString());
            logger.debug("从session获取userId: {}", userId);

            // 确保userId不为null
            if (userId == null) {
                response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
                Map<String, String> errorResponse = new HashMap<>();
                errorResponse.put("error", "无法获取用户信息");
                gson.toJson(errorResponse, response.getWriter());
                return;
            }

            // 从URL路径中获取账号ID
            String pathInfo = request.getPathInfo();
            if (pathInfo == null || pathInfo.length() <= 1) {
                response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
                Map<String, String> errorResponse = new HashMap<>();
                errorResponse.put("error", "缺少账号ID");
                gson.toJson(errorResponse, response.getWriter());
                return;
            }

            // 提取账号ID (格式: /api/accounts/{id})
            String[] pathParts = pathInfo.split("/");
            if (pathParts.length < 2) {
                response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
                Map<String, String> errorResponse = new HashMap<>();
                errorResponse.put("error", "无效的URL路径");
                gson.toJson(errorResponse, response.getWriter());
                return;
            }

            int accountId = Integer.parseInt(pathParts[1]);

            // 删除账号
            boolean success = accountDAO.deleteAccount(accountId, userId);

            if (success) {
                response.setStatus(HttpServletResponse.SC_OK);
                Map<String, Object> successResponse = new HashMap<>();
                successResponse.put("status", "success");
                successResponse.put("message", "账号删除成功");
                gson.toJson(successResponse, response.getWriter());
            } else {
                response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
                Map<String, String> errorResponse = new HashMap<>();
                errorResponse.put("error", "账号删除失败");
                gson.toJson(errorResponse, response.getWriter());
            }
        } catch (NumberFormatException e) {
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            Map<String, String> errorResponse = new HashMap<>();
            errorResponse.put("error", "无效的账号ID");
            gson.toJson(errorResponse, response.getWriter());
        } catch (Exception e) {
            logger.error("删除账号时出错: {}", e.getMessage(), e);
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            Map<String, String> errorResponse = new HashMap<>();
            errorResponse.put("error", "服务器内部错误: " + e.getMessage());
            gson.toJson(errorResponse, response.getWriter());
        }
    }

    /**
     * 将Account对象列表转换为前端需要的响应数据格式
     * 
     * @param accounts 账号列表
     * @return 转换后的响应数据
     */
    private List<Map<String, Object>> convertAccountsToResponseData(List<Account> accounts) {
        List<Map<String, Object>> result = new java.util.ArrayList<>();

        for (Account account : accounts) {
            Map<String, Object> accountMap = new HashMap<>();
            accountMap.put("id", account.getId());
            accountMap.put("userId", account.getUserId());
            accountMap.put("accountType", account.getAccountType());
            accountMap.put("accountId", account.getAccountId());
            accountMap.put("accountName", account.getAccountName());
            accountMap.put("contactEmail", account.getContactEmail());
            accountMap.put("status", account.getStatus());
            accountMap.put("createdAt",
                    account.getCreatedAt() != null ? dateFormat.format(account.getCreatedAt()) : null);
            accountMap.put("expiresAt",
                    account.getExpiresAt() != null ? dateFormat.format(account.getExpiresAt()) : null);
            accountMap.put("isExpired", account.isExpired());

            // 添加icon字段，根据账号类型返回对应的Font Awesome图标
            accountMap.put("icon", getIconByAccountType(account.getAccountType()));

            result.add(accountMap);
        }

        return result;
    }

    /**
     * 根据账号类型返回对应的Font Awesome图标
     * 
     * @param accountType 账号类型
     * @return 图标类名
     */
    private String getIconByAccountType(String accountType) {
        try {
            int typeNum = Integer.parseInt(accountType);
            switch (typeNum) {
                case 1: // 微信
                    return "fa-weixin";
                case 2: // 抖音
                    return "fa-music";
                case 3: // 系统账号
                    return "fa-user";
                case 4: // 邮箱
                    return "fa-envelope-o";
                default:
                    return "fa-user-circle-o";
            }
        } catch (NumberFormatException e) {
            logger.debug("Invalid accountType format: {}", accountType);
            return "fa-user-circle-o";
        }
    }
}